//
//  KLMSmartHome.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/12.
//

import Foundation

/// 家庭列表数据
struct KLMHomeList: Codable {
    let data : HomeListData
    struct HomeListData : Codable {
        let admin : [KLMHomeParticipant]
        let participant : [KLMHomeParticipant]
    }
    ///缓存列表
    static func saveHomeList(list: [KLMHomeParticipant]?) {
        guard let list = list else {
            return
        }
        if list.count > 0 {
            KLMCache.setCache(model: list, key: "HomeParticipantList")
        }
    }
    ///获取列表
    static func getHomeList() -> [KLMHomeParticipant]? {
        return KLMCache.getCache([KLMHomeParticipant].self, key: "HomeParticipantList")
    }
}
struct KLMHomeParticipant : Codable {
//    let tenantcode: String
    let id: Int
    let nickname: String
    let adminId: Int
    let memberNum: Int
    let groupNum: Int
    let meshName: String
    let cityName: String
//    let activeStatus: Int
}
/// 家庭详情信息数据
struct KLMHomeInfoData: Codable {
    var data: KLMHomeInfo
}
struct KLMHomeInfo: Codable {
    let id: Int // mesh ID
    let createTime: String // 创建时间
    let activeStatus: Int // 激活状态
    let meshName: String // 名称
    let adminId: Int // 管理员id
    let syncState: Int // 同步状态
    let meshConfiguration: String // mesh配置信息
    let adminLock: Int // 管理员锁定状态
    let homeRoomCount: Int // 家中房间数量
}
/// 家庭成员列表数据
struct KLMHomeUserList: Codable {
    var data: [KLMHomeUser]
}
enum HomeMemberRoleType: Int, Codable {
    case user = 1000
    case deputyAdmin = 1001
    case Owner = 1002
    case admin = 1003
    case toInviteUser = 1004
}
struct KLMHomeUser: Codable {
    let meshId: Int // 网格ID
    let userId: Int // 用户ID，负数表示待邀请记录
    let username: String // 用户名
    let roleType: Int? // 角色类型，1000普通用户，1002拥有者，1003管理员
    let homeNickname: String // 家中用户昵称
    let inviteCode: String? // 邀请码，不为空表示待邀请用户
    let expiresTimestamp: String // 过期截止时间
    let createTime: String // 用户创建时间
    let adminLock: Int // 管理员锁定状态
    let telephone: String? // 电话号码，可能为空
    let nickname: String? // 账号用户昵称，可能为空
    let email: String? // 邮箱
    
    /// 1000普通成员，1001副管理员，1002是拥有者，1003是管理员，邀请码如果不为空则为待邀请用户
    var userRoleType: HomeMemberRoleType {
        if inviteCode != nil && !inviteCode!.isEmpty {
            return .toInviteUser
        }
        if let role = HomeMemberRoleType.init(rawValue: roleType ?? 1000) {
            return role
        }
        return .user
    }
    var userTypeString: String {
        if let roleType = roleType {
            if roleType == 1000 {
                return "普通用户"
            } else if roleType == 1002 {
                return "拥有者"
            } else if roleType == 1003 {
                return "管理员"
            }
        }
        return ""
    }
    var showExpiresTime: String {
        if userRoleType == .toInviteUser {
            let (expired, time) = Date.getRemainingTime(timestamp: expiresTimestamp)
            if expired {
                return "邀请失效"
            } else {
                return "有效期剩余 \(time)"
            }
        }
        return ""
    }
}
/// 家庭成员详情数据
struct KLMHomeMemberData: Codable {
    var data: KLMHomeMemberInfo
}
struct KLMHomeMemberInfo: Codable {
    let id: Int // 用户ID
    let createTime: String // 用户创建时间
    let username: String // 用户名
    let telephone: String // 电话号码
    let nickname: String // 账号用户昵称
    let homeNickname: String // 家中用户昵称
    let roleType: Int // 角色类型，1000普通用户，1002拥有者，1003管理员
    let adminLock: Int // 管理员锁定状态，推测1代表已锁定，具体含义需结合业务
    let meshAdministrator: Int // 是否具有mesh管理权限，0不具有，1具有
    let meshId: Int // mesh的ID
    
    var isAdmin: Bool {
        meshAdministrator == 1
    }
    var memberRoleType: HomeMemberRoleType {
        if roleType == 1001 {
            return .deputyAdmin
        } else if roleType == 1002 {
            return .Owner
        } else if roleType == 1003 {
            return .admin
        }
        return .user
    }
}

/// 家庭房间数据
struct KLMHomeRoomData: Codable {
    var data: [KLMHomeRoom]
}
struct KLMHomeRoom: Codable {
    let meshId: Int // 家id
    let homeRoomId: Int // 房间id
    let homeRoomName: String // 房间名称
    let homeRoomDeviceCount: Int // 房间设备数量
    let createTime: String // 房间创建时间
    let homeRoomType: Int // 房间类型
}

/// 家庭中房间设备数据
struct KLMHomeRoomDeviceData: Codable {
    var data: [KLMHomeDevice]?
//    var data: [KLMHomeRoomDevice]?
}
struct KLMHomeRoomDevice: Codable {
    let meshId: Int // ID
    let homeRoomId: Int? // 家房间id
    let uuid: String // 设备uuid
    let deviceName: String // 设备名称
    let deviceType: String // 设备类型
}


/// 家中设备联网配置数据
struct KLMProvisionerAddressData: Codable {
    var data: KLMProvisionerAddress
    struct KLMProvisionerAddress: Codable {
        var address: Int
    }
}

struct KLMHomeHeartData: Codable {
    let data: KLMHomeHeart
}
struct KLMHomeHeart: Codable {
    let meshId: Int
    let username: String
    let nickname: String?
    let roleType: Int? //1000普通用户，1002拥有者，1003管理员
    let message: String?
    
    var userRoleType: HomeMemberRoleType? {
        if let role = HomeMemberRoleType.init(rawValue: roleType ?? 0) {
            return role
        }
        return  .user
    }
}

/// 家中所有设备数据
struct KLMHomeDeviceData: Codable {
    var data: [KLMHomeDevice]?
}
struct KLMHomeDevice: Codable {
    
    let meshId: Int
    let homeRoomId: Int? // 家房间id
    let wifiStatus: Int
    let controlMode: Int
    let deviceName: String
    let deviceType: String // 'D0'
    let uuid: String
    let timezone: String
    let homeRoomName: String?
    let currentSceneName: String?
    let bindStatus: Int
    let ledEnable: Int
    let productKey: String?
    let deviceKey: String?
    
    var roomName: String {
        guard let homeRoomName = homeRoomName, !homeRoomName.isEmpty else {
            return "未分配房间"
        }
        return homeRoomName
    }
    var sceneName: String {
        guard let currentSceneName = currentSceneName, !currentSceneName.isEmpty else {
            return "未设置模式"
        }
        return currentSceneName
    }
}

/// RK设备参数数据
struct KLMRKDeviceConfigData: Codable {
    var data: KLMRKDeviceConfig
}
struct KLMRKDeviceConfig: Codable {
    var uuid: String?
    var online: Int?//是否在线 0不在线 1在线
    var upgrade: Int?
    var version: String?//当前版本
    var conserveBrightness: Int?//设置节能亮度，亮度百分比
    var conserveMode: Int?//设置节能模式，0无，1启用
    var conserveTime: Int?//设置节能时间，单位S
    var lookShopSwitch: Int?//设置看店开关，0无，1启用
    var sceneSwitch: Int?//AI模式开关/场景开关，0关，1开
    var flowSwitch: Int?//客流统计开关，0关，1开
    var uploadSwitch: Int?
    var destVersion: String?//最新版本
    var firmwareDesc: String?
    var brightness: Int?
    var ledEnable: Int?//设备开关
    var temperature: Int?
    var sceneEnable: Int?
    var goldenBrightness: Int?
    var sleepAidTime: Int?///黄金光时间 1-60分
    ///线条灯
    var upBrightness: Int?
    var upTemperature: Int?
    var downBrightness: Int?
    var downTemperature: Int?
    
    ///台灯
    var dataReportEnable: Int?//数据上报开关，网关属性，0关，1开
    var debugEnable: Bool?
    
    ///雷达
    var radarEnable: Int?
    var distance: Int?
    var time: Int?
    var ext: Int?
    var indicatorLedOff: Int?///指示灯 0-开 1-关
    ///
    var luxEnable: Int?
    var luxBright: Int?
    var gestureEnable: Int?
    var heatmapDiscreteEnable: Int?
    var iotMsg: String?
    var roomCode: String?///绑定的房间
    var roomName: String?
    var scenePlace: Int?
    var sceneGroup: Int?
    /// AI模式
    var readWriteSceneEnable: Int?//读写模式开关
    var readingSceneEnable: Int?//阅屏模式开关
    var restSceneEnable: Int?//休闲模式开关
    var conserveSceneEnable: Int?//节能模式开关
    
    var seatInductionEnable: Int?//入座感应开关
    var constantLightEnable: Int?//恒照度开关
    /// 情景模式
    var situationalModeEnable: Int?//情景模式开关
    var currentSceneCode: String?//当前场景代码
    var currentSceneName: String?//当前场景名称
    var status: Int?//OTA升级包状态 -1不需要验证 0未验证 1已验证 2验证中 3验证失败
    
    var isOnline: Bool {
        return online == 1
    }
    var isAIMode: Bool {
        return sceneSwitch == 1
    }
    var isSituationalMode: Bool {
        return situationalModeEnable == 1
    }
    var isSeatInductionMode: Bool {
        return seatInductionEnable == 1
    }
    var isConstantLightMode: Bool {
        return constantLightEnable == 1
    }
}

// MARK: - RK设备场景数据
struct KLMRKSceneData: Codable {
    var data: [KLMRKScene]
}
enum RKSceneType: Int, Codable {
    case custom = 0
    case RKSceneType = 1 ///场景识别
    case RKBedType = 2 ///床垫
    case RKGroup = 3 ///场景分组
    case RKTableLamp = 4 ///台灯
    case RKLineLamp = 5 ///线条灯
}
enum RKSceneCodeType: String, Codable {
    case rk_computer
    case rk_book
    case rk_rest
    case rk_conserve//节能
    case rk_lying
    case rk_standing
    case rk_visitor
    case rk_movie
    case rk_meditate
    case rk_electronics
    case rk_lecture
    case rk_meeting
    case rk_daily
    case rk_write //读写
    case rk_reading //阅屏
    case rk_relax //助眠
    case rk_rest_state //休息
    case rk_welcome //欢迎
}
struct KLMRKScene: Codable {
    var id: Int
    var sceneName: String?
    var sceneCode: String?
    var timezoneOffset: Int?
    var roomSelected: Bool?
    var sceneConfig: KLMSceneConfig?
    var sceneButton: Int?
    var sceneType: Int
    var roomName: String?
    var meshId: Int?
    var createTime: String?
//    var sceneData: [Any]?
    var roomCode: String?
    var updateTime: String?
    
    var rkSceneType: RKSceneType? {
        return RKSceneType.init(rawValue: sceneType)
    }
    var rkSceneCodeType: RKSceneCodeType? {
        return RKSceneCodeType.init(rawValue: sceneCode ?? "")
    }
    ///RK场景的名称
    var rkSceneName: String? {
        var name: String?
        switch rkSceneCodeType {
        case .rk_computer:
            name = KLMLocalizable.LANGLOC("Working")
        case .rk_book:
            name = KLMLocalizable.LANGLOC("Reading")
        case .rk_rest:
            name = KLMLocalizable.LANGLOC("Resting")
        case .rk_conserve:
            name = KLMLocalizable.LANGLOC("Conserving")
        case .rk_electronics:
            name = KLMLocalizable.LANGLOC("Electronics")
        case .rk_lecture:
            name = KLMLocalizable.LANGLOC("Lecture")
        case .rk_meditate:
            name = KLMLocalizable.LANGLOC("Meditate")
        case .rk_meeting:
            name = KLMLocalizable.LANGLOC("Meeting")
        case .rk_movie:
            name = KLMLocalizable.LANGLOC("Movie")
        case .rk_visitor:
            name = KLMLocalizable.LANGLOC("Visitor")
        case .rk_lying:
            name = KLMLocalizable.LANGLOC("Experience")
        case .rk_standing:
            name = KLMLocalizable.LANGLOC("Display")
        case .rk_daily:
            name = KLMLocalizable.LANGLOC("Walk-around")
        case .rk_write:
            name = KLMLocalizable.LANGLOC("Read/Write")
        case .rk_reading:
            name = KLMLocalizable.LANGLOC("Screen")
        case .rk_relax:
            name = KLMLocalizable.LANGLOC("Sleep-aid")
        case .rk_rest_state:
            name = KLMLocalizable.LANGLOC("Relax")
        case .rk_welcome:
            name = KLMLocalizable.LANGLOC("Welcome")
        default:
            name = sceneName
            break
        }
        return name
    }
}

struct KLMSceneConfig: Codable {
    // 亮度
    var downBrightness: Int?
    var upBrightness: Int?
    // 色温相关
    var upTemperature: Int?        // 色温值（K）
    var downTemperature: Int?
    
    // 时间相关（字符串类型，可能为空）
    var upStartTime: String?       // 开始时间
    var upEndTime: String?         // 结束时间
    var downStartTime: String?
    var downEndTime: String?
    
    // 执行频率 0未选中 1仅1次 2周1到周5 3每天 4法定工作日 5自定义
    var downFrequency: Int?
    var upFrequency: Int?
    
    var upFadeUp: Int? // 渐亮时间 -1未选中 0-其他值 单位秒
    var upFadeDown: Int? // 渐灭时间 -1未选中 0-其他值 单位秒
    var downFadeUp: Int?
    var downFadeDown: Int?
    
    // 定时设置 单位分钟
    var upStateDuration: Int?
    var downStateDuration: Int?
    
    var upWeek: String? // 1111111，每1位对应周1-周7，0未选，1选
    var downWeek: String?
    
    
    init(downBrightness: Int? = nil, upBrightness: Int? = nil, upTemperature: Int? = nil, downTemperature: Int? = nil, upStartTime: String? = nil, upEndTime: String? = nil, downStartTime: String? = nil, downEndTime: String? = nil, downFrequency: Int? = nil, upFrequency: Int? = nil, upFadeUp: Int? = nil, upFadeDown: Int? = nil, downFadeUp: Int? = nil, downFadeDown: Int? = nil, upStateDuration: Int? = nil, downStateDuration: Int? = nil, upWeek: String? = nil, downWeek: String? = nil) {
        self.downBrightness = downBrightness
        self.upBrightness = upBrightness
        self.upTemperature = upTemperature
        self.downTemperature = downTemperature
        self.upStartTime = upStartTime
        self.upEndTime = upEndTime
        self.downStartTime = downStartTime
        self.downEndTime = downEndTime
        self.downFrequency = downFrequency
        self.upFrequency = upFrequency
        self.upFadeUp = upFadeUp
        self.upFadeDown = upFadeDown
        self.downFadeUp = downFadeUp
        self.downFadeDown = downFadeDown
        self.upStateDuration = upStateDuration
        self.downStateDuration = downStateDuration
        self.upWeek = upWeek
        self.downWeek = downWeek
    }
}


struct KLMCreatedSceneData: Codable {
    var data: KLMCreatedScene
}
struct KLMCreatedScene: Codable {
    var id: Int?
    var meshId: Int?
    var sceneName: String?
    var sceneType: Int?
    var sceneCode: String?
}
